package br.com.firula.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;

public class CepUtils {
	
	public static HashMap<String, String> fromCepToAddress(String cep){
		HashMap<String, String> address = new HashMap<String, String>();
		
		try {
			URL url = new URL("http://comercio.locaweb.com.br/correios/calcula_sedex.asp?cepDest="+cep+"&urlback=http://www.isnow.com.br/cep_Loja.html");
			
			URLConnection conn = url.openConnection();
			conn.setConnectTimeout(10000);
			conn.setReadTimeout(10000);
			
			String page = "";
			BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
	        while ((line = rd.readLine()) != null) {
	        	page += line;
	        }
	        
	        try {
	        	rd.close();
	        } catch (Exception e) {
				e.printStackTrace();
			}
			
	        String restante = page;
	        System.out.println("RestanteCepUtils=" + restante);
	        while (restante.indexOf("name=\"") != -1){
	        	
	        	restante = restante.substring(restante.indexOf("name=\"")+6, restante.length());
	        	String name = new String(restante.substring(0, restante.indexOf("\"")));
	        	restante = restante.substring(restante.indexOf("\""), restante.length());
	        	
	        	restante = restante.substring(restante.indexOf("value=\"")+7, restante.length());
	        	String value = new String(restante.substring(0, restante.indexOf("\"")));
	        	restante = restante.substring(restante.indexOf("\""), restante.length());
	        	
	        	address.put(name, value);
	        }
			
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("TEMPO EXCEDIDO");
			e.printStackTrace();
		}
		/*
		if(cep.equals("04829-270")){
			address.put("estado", "MG");
			address.put("bairro", "whatever");
			address.put("cidade", "Espero Que Funcione");
			address.put("retorno", "Rua mimimi");
		}
		else{
			address.put("estado", "");
			address.put("bairro", "");
			address.put("cidade", "");
			address.put("retorno", "");	
		} */
        return address;
	}
	
	public static void main(String args[]) {
		fromCepToAddress("13084195");
	}
}
